package com.googlecode.eightqueenshaggle;

import java.util.ArrayList;

import org.haggle.Attribute;
import org.haggle.DataObject;
import org.haggle.Interface;
import org.haggle.Node;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;



public class SolutionExplorerViewController extends Activity implements OnClickListener{


	//This should come out of haggle
	public int amountSolutions;
	
	static final int DIALOG_PRESENT_SOLUTION = 0;
	ArrayList<SolutionObject> solObjArray=null;
	Node[] solexpneigh = null;
	
	public EightQueens eqHandler;
	
	private android.os.Vibrator vibrator = null;
	
	public Gallery g = null;
	public ListView nlv = null;
	public SolutionExplorerImageAdapter seia = null;
	public NodeAdapter nodeAdpt = null;
	
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.solution_explorer);

		solObjArray = HaggleConnector.getInstance().solobjs;
		solexpneigh = HaggleConnector.getInstance().neighs;
		//amountSolutions=solObjArray.size();
		
		//register globally
		eqHandler=(EightQueens) this.getApplication();
		eqHandler.solutionExplorerViewHandler=this;
		
		//set up the image adapter
		seia = new SolutionExplorerImageAdapter(this);
		
	    //set up the gallery
		g = (Gallery) findViewById(R.id.gallery);
	    g.setAdapter(seia);
		
		
	    g.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView parent, View v, int position, long id) {
	            
	        	
	        	//Toast.makeText(SolutionExplorerViewController.this, "" + position, Toast.LENGTH_SHORT).show();
	        	showDialog(position);
	        
	        	
	    		/*Context mContext = getApplicationContext();
	    		Dialog dialog= new Dialog(mContext);
	    		
	        	dialog.setContentView(R.layout.present_solution_dialog);
	        	dialog.setTitle("Custom Dialog");

	        	TextView text = (TextView) dialog.findViewById(R.id.TVsolution);
	        	text.setText("Hello, this is a custom dialog!");
	        	ImageView image = (ImageView) dialog.findViewById(R.id.IVsolution);
	        	image.setImageResource(R.drawable.logo_queen);
	        	dialog.show();*/
	        	
	        
	        }
	    });
		
	    //set up the node adapter
	    nodeAdpt = new NodeAdapter(this);
	    
	    //set up the neigh list view
	    //TODO: The list view is still a little bit ugly, someone has an idea how to change that?
		nlv = (ListView) findViewById(R.id.ListViewNeighbors);
		
		TextView tv = new TextView(this);
		
		/*ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
				R.layout.solution_explorer_neighbor, projectMembers);*/
		
		//android.R.layout.simple_list_item_1
		
		nlv.setAdapter(nodeAdpt);
		nlv.setTextFilterEnabled(false);
		
		
		
	}
	
	


	protected Dialog onCreateDialog(int id) {
		
		Dialog dialog= new Dialog(this);
	   
    	dialog.setContentView(R.layout.present_solution_dialog);
    	
    	//every solution is given a random id here
    	dialog.setTitle("Solution"+id);

    	
    	TextView text = (TextView) dialog.findViewById(R.id.TVsolution);
    	
    	String textString = 
    			this.solObjArray.get(id).myPuzzle.puzzleName+"\n"+
    			"playerName: "+this.solObjArray.get(id).playerName+"\n"+
    			
    			"dim1: "+this.solObjArray.get(id).myPuzzle.dim1+"\n"+
    			"dim2: "+this.solObjArray.get(id).myPuzzle.dim2+"\n"+
  
    			"Solution Coords:\n";
    			
    	//now we attach the coordinates in a textual form
    	for(String coord : this.solObjArray.get(id).mySolution.getCoordString().split(";")){
    		
    		textString += "( "+coord.split(" ")[0]+ " ; " + coord.split(" ")[1] + " )\n";
    		
    	}	
    
    	text.setText(textString);
    	
    	ImageView image = (ImageView) dialog.findViewById(R.id.IVsolution);
    	image.setImageResource(R.drawable.logo_queen);
	       	    	
	
	    return dialog;
	    
		/*//Context mContext = getApplicationContext();
		Dialog dialog= new Dialog(this);
	    
		switch(id) {
	    case DIALOG_PRESENT_SOLUTION:
	        

        	dialog.setContentView(R.layout.present_solution_dialog);
        	dialog.setTitle("Solution Nr. 42");

        	TextView text = (TextView) dialog.findViewById(R.id.TVsolution);
        	text.setText("Textual representation of a solution");
        	ImageView image = (ImageView) dialog.findViewById(R.id.IVsolution);
        	image.setImageResource(R.drawable.logo_queen);
	        
	    	
	    	break;
	    default:
	        dialog = null;
	    }
	    return dialog;*/
	
	}
	
	/*final String[] projectMembers = new String [] {
		
		"Shuo", "Ying", "Volker"
		
};*/

	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}


	//update the GUI, when sth. happens in Haggle
    public class DataUpdater implements Runnable {
    	int type;
    	/*DataObject dObj = null;
    	Node[] neighbors = null;*/
	
	public DataUpdater(int pType)
	{
		this.type = pType;
	}

    public void run() {
		Log.d("**** SolutionExplorer: DataUpdater", "Running data updater, thread id=" + Thread.currentThread().getId());
    	
		//make the phone vibrate
		vibrator = (android.os.Vibrator)getSystemService(VIBRATOR_SERVICE);
		long[] pattern = { 0, 300, 100, 400 };
		vibrator.vibrate(pattern, -1);
		
		switch(type) {
    	
		case org.haggle.EventHandler.EVENT_NEIGHBOR_UPDATE:
    		Log.d("**** SolutionExplorer: DataUpdater", "Event neighbor update");
    		
    		//TODO: Redraw NeighborListView
    		solexpneigh = HaggleConnector.getInstance().neighs;
    		nodeAdpt.updateNeighbors(solexpneigh);
    		
    		break;
    	
		case org.haggle.EventHandler.EVENT_NEW_DATAOBJECT:
    		Log.d("**** SolutionExplorer: DataUpdater", "Event new data object");
	        
    		//Redraw Gallery
    		seia.notifyDataSetChanged();
    		
    		break;
    	}
		Log.d("**** SolutionExplorer: DataUpdater", "data updater done");
    }

}

    //stolen from PhotoView.java
    class NodeAdapter extends BaseAdapter {
    	
    	private Context mContext;
    	private Node[] neighbors = null;

    	public NodeAdapter(Context mContext) {
    		this.mContext = mContext;
    	}
    	public int getCount() {
    		if (neighbors == null || neighbors.length == 0)
    			return 1;
    		else
    			return neighbors.length;
    	}

    	public Object getItem(int position) {
    		return position;
    	}

    	public long getItemId(int position) {
    		return position;
    	}
    	public synchronized void updateNeighbors(Node[] neighs) {
    		neighbors = neighs;

    		Log.d("**** NodeAdapter", "Updated neighbor array");
    		notifyDataSetChanged();
    	}

        public void refresh() {
        	notifyDataSetChanged();
        }
        
    	public View getView(int position, View convertView, ViewGroup parent) {    		
    		TextView tv;
    		
    		if (convertView == null) {
                tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.neighbor_list_item, parent, false);
            } else {
                tv = (TextView) convertView;
            }

    		if (neighbors == null || neighbors.length == 0) {
    			tv.setText("No active neighbors");

    		} else {
    			Node node = neighbors[position];
    			
    			String ifaceInfo = new String(" [");
    			for (int i=0; i<node.getNumInterfaces(); i++) {
    				Interface iface = node.getInterfaceN(i);
    				if (iface != null) {
	    				if (iface.getType() == Interface.IFTYPE_BLUETOOTH && iface.getStatus() == Interface.IFSTATUS_UP) {
	    					ifaceInfo += " BT";
	    				}
	    				if (iface.getType() == Interface.IFTYPE_ETHERNET && iface.getStatus() == Interface.IFSTATUS_UP) {
	    					ifaceInfo += " WiFi";
	    				}
    				}
    			}
    			ifaceInfo += " ]";
    			tv.setText(node.getName() + ifaceInfo);
    		}
    		return tv;
    	}
    	public Node getNode(int pos) {
    		if (pos < 0 || pos > neighbors.length - 1) 
    			return null;
    		
    		return neighbors[pos];
    	}
    	public synchronized Node[] getNodes() {
    		return neighbors.clone();
    	}
    	public String getInformation(int position) {
    		if ((neighbors.length > 0) && (position >= 0)) {
    			Node n = neighbors[position];
    			return n.toString();
    		} else {
    			return "Node Information";
    		}
    	}
    }
    
    
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(this, MainMenuController.class);
			startActivity(intent);
			finish();
        	//moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
}